package com.aloda.api.config;

import feign.Logger;
import feign.RequestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * OpenFeign默认配置
 */
public class DefaultFeignConfig {

    private static final String USER_TOKEN_NAME = "authorization";

    /**
     * 全量记录日志
     * @return
     */
    @Bean
    public Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }

    /**
     * OpenFeign调用请求传递用户token供下游服务使用
     * @return
     */
    @Bean
    public RequestInterceptor userInfoRequestInterceptor() {
        return requestTemplate -> {
            // 获取当前请求的上下文
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes != null) {
                // 获取当前请求
                HttpServletRequest request = attributes.getRequest();
                // 从请求头中获取令牌信息
                String token = request.getHeader(USER_TOKEN_NAME);
                if (token != null) {
                    // 将令牌信息添加到Feign请求头中
                    requestTemplate.header(USER_TOKEN_NAME, token);
                }
            }
        };
    }
}
